Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data

In [3]:
# Load pickled data
import pickle
import numpy as np
from numpy import newaxis
import cv2

# TODO: Fill this in based on where you saved the training and testing data

training_file = 'train.p'
validation_file= 'valid.p'
testing_file = 'test.p'

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']

print('Data opened')
print('X_train shape', X_train.shape)
print('y_train shape', y_train.shape)
print('X_test shape', X_test.shape)
print('y_test shape', y_test.shape)
print('X_valid shape', X_valid.shape)
print('y_valid shape', y_valid.shape)
Data opened
X_train shape (34799, 32, 32, 3)
y_train shape (34799,)
X_test shape (12630, 32, 32, 3)
y_test shape (12630,)
X_valid shape (4410, 32, 32, 3)
y_valid shape (4410,)

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas

In [4]:
### Replace each question mark with the appropriate value. 
### Use python, pandas or numpy methods rather than hard coding the results

# TODO: Number of training examples
n_train = len(X_train)

# TODO: Number of testing examples.
n_test = len(X_test)

# TODO: What's the shape of an traffic sign image?
image_shape = X_train[1].shape

# TODO: How many unique classes/labels there are in the dataset.
n_classes = len(np.unique(y_train))

print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)

print('number of images in Y train set =', len(y_train))
print('number of images in Y test set =', len(y_test))
Number of training examples = 34799
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Number of classes = 43
number of images in Y train set = 34799
number of images in Y test set = 12630
In [5]:
# print out signnames.csv (Class ID, Sign Name)

import csv
sign_names = []
with open('signnames.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        content = list(row[i] for i in row)
        print(content)
['Speed limit (20km/h)', '0']
['Speed limit (30km/h)', '1']
['Speed limit (50km/h)', '2']
['Speed limit (60km/h)', '3']
['Speed limit (70km/h)', '4']
['Speed limit (80km/h)', '5']
['End of speed limit (80km/h)', '6']
['Speed limit (100km/h)', '7']
['Speed limit (120km/h)', '8']
['No passing', '9']
['No passing for vehicles over 3.5 metric tons', '10']
['Right-of-way at the next intersection', '11']
['Priority road', '12']
['Yield', '13']
['Stop', '14']
['No vehicles', '15']
['Vehicles over 3.5 metric tons prohibited', '16']
['No entry', '17']
['General caution', '18']
['Dangerous curve to the left', '19']
['Dangerous curve to the right', '20']
['Double curve', '21']
['Bumpy road', '22']
['Slippery road', '23']
['Road narrows on the right', '24']
['Road work', '25']
['Traffic signals', '26']
['Pedestrians', '27']
['Children crossing', '28']
['Bicycles crossing', '29']
['Beware of ice/snow', '30']
['Wild animals crossing', '31']
['End of all speed and passing limits', '32']
['Turn right ahead', '33']
['Turn left ahead', '34']
['Ahead only', '35']
['Go straight or right', '36']
['Go straight or left', '37']
['Keep right', '38']
['Keep left', '39']
['Roundabout mandatory', '40']
['End of no passing', '41']
['End of no passing by vehicles over 3.5 metric tons', '42']

Include an exploratory visualization of the dataset

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections.

In [6]:
### visualizatio of signs and labels
import matplotlib.pyplot as plt
import random
from pandas.io.parsers import read_csv
%matplotlib inline

fig, axs = plt.subplots(4,5, figsize=(10,6))
fig.subplots_adjust(hspace = .2, wspace = .001)
axs = axs.ravel()

for i in range(20):
    i_random = random.randint(0,len(X_train))
    #print('Sign', i_random)
    axs[i].axis('off')
    axs[i].imshow(X_train[i_random])
    axs[i].set_title(y_train[i_random])
In [43]:
# Disribution of data in test, train and validation dataset

def distribution(class_labels, text):
    plt.figure(figsize=(10, 4))
    examples_per_class = np.bincount(class_labels)
    num_classes = len(examples_per_class)
    plt.bar(np.arange(num_classes), examples_per_class, 0.8, color='b', label='Inputs per class')
    plt.xlabel('Class ID')
    plt.ylabel('NUmber of images')
    plt.title(text)
    plt.show()   
    
distribution(y_train, 'Distribution of Training Examples')
distribution(y_valid, 'Distribution of Validation Examples')
distribution(y_test, 'Distribution of Test Examples')

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

NOTE: The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

Pre-process the Data Set (normalization, grayscale, etc.)

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

In [14]:
# Convert to gray scale
def gray_scale(data):
    return np.array([cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) for image in data])

X_train_gray = gray_scale(X_train)
X_test_gray = gray_scale(X_test)
X_valid_gray = gray_scale(X_valid)

# Histogram Equalization
def histogram(data):
    return np.array([cv2.equalizeHist(image) for image in data])

X_train_hist = histogram(X_train_gray)
X_test_hist = histogram(X_test_gray)
X_valid_hist = histogram(X_valid_gray)

# Reshape for conv layer
X_train_test = X_train_hist[..., newaxis]
X_test_test = X_test_hist[..., newaxis]
X_valid_test = X_valid_hist[..., newaxis]
print('X_train_test shape after adding newaxis', X_train_test.shape)
print('X_test_test shape after adding newaxis', X_test_test.shape)

# Normalization with Gray Scale and Histogram
X_train_test = X_train_test / np.std(X_train_test, axis = 0)
X_test_test = X_test_test / np.std(X_test_test, axis = 0)
X_valid_test = X_valid_test / np.std(X_valid_test, axis = 0)
print('X_train_test shape', X_train_test.shape)
print('X_test_test shape', X_test_test.shape)
print('X_valid_test shape', X_valid_test.shape)

X_train = X_train_test
X_test = X_test_test
X_valid = X_valid_test

print('X Train normalize', np.mean(X_train_test))
print('X Test normalize', np.mean(X_test_test))

print('len X_train  ', len(X_train_test))
print('len X_test  ',len(X_test_test))


print('TEST new axis') #
print('X_test', X_train_test[1].shape)
print('X_valid', X_valid_test[1].shape)
X_train_test shape after adding newaxis (34799, 32, 32, 1)
X_test_test shape after adding newaxis (12630, 32, 32, 1)
X_train_test shape (34799, 32, 32, 1)
X_test_test shape (12630, 32, 32, 1)
X_valid_test shape (4410, 32, 32, 1)
X Train normalize 1.87209831993
X Test normalize 1.86566802053
len X_train   34799
len X_test   12630
TEST new axis
X_test (32, 32, 1)
X_valid (32, 32, 1)
In [15]:
### visualizatio of signs and labels after pre processing

fig, axs = plt.subplots(4,5, figsize=(10,6))
fig.subplots_adjust(hspace = .2, wspace = .001)
axs = axs.ravel()

for i in range(20):
    i_random = random.randint(0,len(X_train))
    #print('Sign', i_random)
    axs[i].axis('off')
    axs[i].imshow(X_train[i_random].squeeze())
    axs[i].set_title(y_train[i_random])

Model Architecture

In [16]:
### Define your architecture here.
### Feel free to use as many code cells as needed.

# shuffle normalized data
from sklearn.utils import shuffle

X_train, y_train = shuffle(X_train, y_train)

I have used Architecture from research paper Multi-Column Deep Neural Network for Traffic Sign Classification http://people.idsia.ch/~juergen/nn2012traffic.pdf

  • Layer 1: Convolutional. Input = 32x32x1. Output = 26x26x100.
       - Pooling. Input = 26x26x100. Output = 13x13x100.
  • Layer 2: Convolutional. Output = 10x10x150.
       - Pooling. Input = 10x10x16. Output = 5x5x150.
  • Layer 3: Fully Connected. Input = 250. Output = 200.
  • Layer 4: Fully Connected. Input = 200. Output = 43.
In [17]:
import tensorflow as tf
from sklearn.utils import shuffle

EPOCHS = 100
BATCH_SIZE = 192

from tensorflow.contrib.layers import flatten
def mcdnn(x):    
    # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
    mu = 0
    sigma = 0.1
            
    # Layer 1: Convolutional. Input = 32x32x1. Output = 26x26x100.
    F_W = tf.Variable(tf.truncated_normal((7,7,1,100), mean = mu, stddev = sigma)) # Change W parameters
    F_b = tf.Variable(tf.zeros(100)) # is bias zero
    strides = 1
    conv1 = tf.nn.conv2d(x, F_W, strides=[1,strides,strides,1], padding = 'VALID') + F_b
    
    # Activation.
    conv1 = tf.nn.relu(conv1)
    
    # Pooling. Input = 26x26x100. Output = 13x13x100.
    conv1 = tf.nn.max_pool(conv1, ksize=[1,2,2,1],strides=[1,2,2,1],padding='VALID')
    print("Conv 1 shape:",conv1.get_shape())
    
    # Layer 2: Convolutional. Output = 10x10x150.
    F_W_conv2 = tf.Variable(tf.truncated_normal((4,4,100,150), mean = mu, stddev = sigma))
    F_b_conv2 = tf.Variable(tf.zeros(150))
    conv2 = tf.nn.conv2d(conv1,F_W_conv2, strides=[1,1,1,1],padding='VALID')+F_b_conv2
    
    # Activation.
    conv2 = tf.nn.relu(conv2)
    
    # Pooling. Input = 10x10x16. Output = 5x5x150.
    conv2 = tf.nn.max_pool(conv2,ksize=[1,2,2,1],strides=[1,2,2,1],padding='VALID')
    print("Conv 2 shape:",conv2.get_shape())
    
    ### Removed last convolutional layer from MCDNN network due i felt it was not needed for better accuracy
    ### After removal of this layer accuracy jumped
    '''
    # TODO: Layer 2: Convolutional. Output = 2x2x100.
    F_W_conv3 = tf.Variable(tf.truncated_normal((4,4,150,250), mean = mu, stddev = sigma))
    F_b_conv3 = tf.Variable(tf.zeros(250)) # is bias zero
    conv3 = tf.nn.conv2d(conv2,F_W_conv3, strides=[1,1,1,1],padding='VALID')+F_b_conv3
    
    # TODO: Activation.
    conv3 = tf.nn.relu(conv3)
        
    # Pooling. Input = 10x10x16. Output = 1x1x250.
    conv3 = tf.nn.max_pool(conv3,ksize=[1,2,2,1],strides=[1,2,2,1],padding='VALID')
    print("Conv 3 shape:",conv3.get_shape())
    '''
    # Flatten. Input = 3750. Output = 250.
    fc0 = flatten(conv2)
    print("fc0 shape:",fc0.get_shape())
    fc0 = tf.nn.dropout(fc0, keep_prob)
    
    # Layer 3: Fully Connected. Input = 250. Output = 200.
    fc1_W = tf.Variable(tf.truncated_normal(shape=(3750, 200), mean = mu, stddev = sigma))
    fc1_b = tf.Variable(tf.zeros(200))
    fc1   = tf.matmul(fc0, fc1_W) + fc1_b
    
    # Activation.
    fc1 = tf.nn.relu(fc1)
    print("fc1 shape:",fc1.get_shape())
    
    # Layer 4: Fully Connected. Input = 200. Output = 43.
    fc2_W = tf.Variable(tf.truncated_normal(shape=(200, 43), mean = mu, stddev = sigma))
    fc2_b = tf.Variable(tf.zeros(43))
    fc2   = tf.matmul(fc1, fc2_W) + fc2_b
        
    logits = fc2
    return logits

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the test set but low accuracy on the validation set implies overfitting.

In [1]:
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected, 
### the accuracy on0 the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
In [18]:
# Note
x = tf.placeholder(tf.float32, (None, 32, 32, 1))
y = tf.placeholder(tf.int32, (None))
one_hot_y = tf.one_hot(y, 43)
keep_prob = tf.placeholder(tf.float32)

# Note
rate = 0.001

logits = mcdnn(x)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, one_hot_y)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)

correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()

def evaluate(X_data, y_data):
    num_examples = len(X_data)
    total_accuracy = 0
    sess = tf.get_default_session()
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
        accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: 1})
        total_accuracy += (accuracy * len(batch_x))
    return total_accuracy / num_examples
Conv 1 shape: (?, 13, 13, 100)
Conv 2 shape: (?, 5, 5, 150)
fc0 shape: (?, 3750)
fc1 shape: (?, 200)
In [21]:
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    num_examples = len(X_train)
    
    print("Training...")
    print()
    for i in range(EPOCHS):
        X_train, y_train = shuffle(X_train, y_train)
        for offset in range(0, num_examples, BATCH_SIZE):
            end = offset + BATCH_SIZE
            batch_x, batch_y = X_train[offset:end], y_train[offset:end]
            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: 0.5})
            
        validation_accuracy = evaluate(X_valid, y_valid)
        print("EPOCH {} ...".format(i+1))
        print("Validation Accuracy = {:.3f}".format(validation_accuracy))
        print()
        
    saver.save(sess, './lenet') # I did not change name of saved model
    print("Model saved")
Training...

EPOCH 1 ...
Validation Accuracy = 0.786

EPOCH 2 ...
Validation Accuracy = 0.856

EPOCH 3 ...
Validation Accuracy = 0.896

EPOCH 4 ...
Validation Accuracy = 0.911

EPOCH 5 ...
Validation Accuracy = 0.909

EPOCH 6 ...
Validation Accuracy = 0.923

EPOCH 7 ...
Validation Accuracy = 0.914

EPOCH 8 ...
Validation Accuracy = 0.913

EPOCH 9 ...
Validation Accuracy = 0.924

EPOCH 10 ...
Validation Accuracy = 0.923

EPOCH 11 ...
Validation Accuracy = 0.941

EPOCH 12 ...
Validation Accuracy = 0.933

EPOCH 13 ...
Validation Accuracy = 0.932

EPOCH 14 ...
Validation Accuracy = 0.911

EPOCH 15 ...
Validation Accuracy = 0.931

EPOCH 16 ...
Validation Accuracy = 0.936

EPOCH 17 ...
Validation Accuracy = 0.950

EPOCH 18 ...
Validation Accuracy = 0.931

EPOCH 19 ...
Validation Accuracy = 0.943

EPOCH 20 ...
Validation Accuracy = 0.936

EPOCH 21 ...
Validation Accuracy = 0.949

EPOCH 22 ...
Validation Accuracy = 0.940

EPOCH 23 ...
Validation Accuracy = 0.937

EPOCH 24 ...
Validation Accuracy = 0.941

EPOCH 25 ...
Validation Accuracy = 0.937

EPOCH 26 ...
Validation Accuracy = 0.947

EPOCH 27 ...
Validation Accuracy = 0.956

EPOCH 28 ...
Validation Accuracy = 0.930

EPOCH 29 ...
Validation Accuracy = 0.934

EPOCH 30 ...
Validation Accuracy = 0.933

EPOCH 31 ...
Validation Accuracy = 0.934

EPOCH 32 ...
Validation Accuracy = 0.939

EPOCH 33 ...
Validation Accuracy = 0.947

EPOCH 34 ...
Validation Accuracy = 0.951

EPOCH 35 ...
Validation Accuracy = 0.940

EPOCH 36 ...
Validation Accuracy = 0.940

EPOCH 37 ...
Validation Accuracy = 0.941

EPOCH 38 ...
Validation Accuracy = 0.949

EPOCH 39 ...
Validation Accuracy = 0.936

EPOCH 40 ...
Validation Accuracy = 0.930

EPOCH 41 ...
Validation Accuracy = 0.943

EPOCH 42 ...
Validation Accuracy = 0.951

EPOCH 43 ...
Validation Accuracy = 0.941

EPOCH 44 ...
Validation Accuracy = 0.938

EPOCH 45 ...
Validation Accuracy = 0.949

EPOCH 46 ...
Validation Accuracy = 0.946

EPOCH 47 ...
Validation Accuracy = 0.947

EPOCH 48 ...
Validation Accuracy = 0.943

EPOCH 49 ...
Validation Accuracy = 0.943

EPOCH 50 ...
Validation Accuracy = 0.947

EPOCH 51 ...
Validation Accuracy = 0.939

EPOCH 52 ...
Validation Accuracy = 0.943

EPOCH 53 ...
Validation Accuracy = 0.951

EPOCH 54 ...
Validation Accuracy = 0.951

EPOCH 55 ...
Validation Accuracy = 0.946

EPOCH 56 ...
Validation Accuracy = 0.949

EPOCH 57 ...
Validation Accuracy = 0.957

EPOCH 58 ...
Validation Accuracy = 0.952

EPOCH 59 ...
Validation Accuracy = 0.942

EPOCH 60 ...
Validation Accuracy = 0.952

EPOCH 61 ...
Validation Accuracy = 0.937

EPOCH 62 ...
Validation Accuracy = 0.955

EPOCH 63 ...
Validation Accuracy = 0.945

EPOCH 64 ...
Validation Accuracy = 0.943

EPOCH 65 ...
Validation Accuracy = 0.943

EPOCH 66 ...
Validation Accuracy = 0.956

EPOCH 67 ...
Validation Accuracy = 0.955

EPOCH 68 ...
Validation Accuracy = 0.945

EPOCH 69 ...
Validation Accuracy = 0.949

EPOCH 70 ...
Validation Accuracy = 0.941

EPOCH 71 ...
Validation Accuracy = 0.941

EPOCH 72 ...
Validation Accuracy = 0.948

EPOCH 73 ...
Validation Accuracy = 0.944

EPOCH 74 ...
Validation Accuracy = 0.946

EPOCH 75 ...
Validation Accuracy = 0.948

EPOCH 76 ...
Validation Accuracy = 0.956

EPOCH 77 ...
Validation Accuracy = 0.938

EPOCH 78 ...
Validation Accuracy = 0.949

EPOCH 79 ...
Validation Accuracy = 0.944

EPOCH 80 ...
Validation Accuracy = 0.953

EPOCH 81 ...
Validation Accuracy = 0.947

EPOCH 82 ...
Validation Accuracy = 0.951

EPOCH 83 ...
Validation Accuracy = 0.951

EPOCH 84 ...
Validation Accuracy = 0.944

EPOCH 85 ...
Validation Accuracy = 0.939

EPOCH 86 ...
Validation Accuracy = 0.948

EPOCH 87 ...
Validation Accuracy = 0.956

EPOCH 88 ...
Validation Accuracy = 0.952

EPOCH 89 ...
Validation Accuracy = 0.954

EPOCH 90 ...
Validation Accuracy = 0.943

EPOCH 91 ...
Validation Accuracy = 0.937

EPOCH 92 ...
Validation Accuracy = 0.947

EPOCH 93 ...
Validation Accuracy = 0.955

EPOCH 94 ...
Validation Accuracy = 0.940

EPOCH 95 ...
Validation Accuracy = 0.950

EPOCH 96 ...
Validation Accuracy = 0.945

EPOCH 97 ...
Validation Accuracy = 0.944

EPOCH 98 ...
Validation Accuracy = 0.945

EPOCH 99 ...
Validation Accuracy = 0.948

EPOCH 100 ...
Validation Accuracy = 0.950

Model saved

Evaluate Model

In [19]:
with tf.Session() as sess:
    saver.restore(sess, tf.train.latest_checkpoint('.'))

    test_accuracy = evaluate(X_test, y_test)
    print("Test Accuracy = {:.3f}".format(test_accuracy))
Test Accuracy = 0.940

Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Load and Output the Images

In [20]:
# I have several sign images of different sizes
# I will firs resize them to 32x32 size
import os
import cv2

# resize images to 32x32
def resize_newimage(image_name):
    image = cv2.imread(image_name)
    image = cv2.resize(image,(32,32))
    return image

images = np.array([resize_newimage('new_signs/'+ img_name) for img_name in os.listdir('new_signs')])

# show new images of new signs
for i,image in enumerate(images):
    plt.imshow(image)
    plt.show()
    print('Images shape', images[i].shape)
Images shape (32, 32, 3)
Images shape (32, 32, 3)
Images shape (32, 32, 3)
Images shape (32, 32, 3)
Images shape (32, 32, 3)
Images shape (32, 32, 3)
Images shape (32, 32, 3)
Images shape (32, 32, 3)
Images shape (32, 32, 3)
In [21]:
# Convert to gray scale
def gray_scale(data):
    return np.array([cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) for image in data])

images_gray = gray_scale(images)

print('New Sign Images Gray shape', images_gray.shape)

# Histogram Equalization
def histogram(data):
    return np.array([cv2.equalizeHist(image) for image in data])

images_hist = histogram(images_gray)

# Reshape for conv layer
images_test = images_hist[..., newaxis]

# Normalization with Gray Scale and Histogram
images_test = images_test / np.std(images_test, axis = 0)
print('New Sign Images Test Shape', images_test.shape)
print('New Sign Images Test normalize', np.mean(images_test))


print('len images_test  ', len(images_test))

print('TEST new axis') #
print('New Sign Images_test shape', images_test[1].shape)
New Sign Images Gray shape (9, 32, 32)
New Sign Images Test Shape (9, 32, 32, 1)
New Sign Images Test normalize 1.67519682751
len images_test   9
TEST new axis
New Sign Images_test shape (32, 32, 1)
In [25]:
for image in images_test:
    plt.imshow(image.squeeze())
    plt.show()

Predict the Sign Type for Each Image

In [26]:
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.

# Evaluating new sign images with saved training model. Also adding labels so we can see how model works.
# below you will see that if we change keep_prob: 0.5 accuracy increases. I would love to train model for this but 
# it would take a long time since i am doing it on CPU

labels = [1,34, 12, 25, 25, 28, 2, 14, 14]

with tf.Session() as sess:
    saver.restore(sess, ('./lenet'))
    new_accuracy = evaluate(images_test, labels)
    print("New Images Accuracy = {:.3f}".format(new_accuracy))
New Images Accuracy = 0.667
In [27]:
# Testing data within previous model to see will it predict better
# Testing tf.nn.top_k
# Model does not make sense due its same as above :)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    saver = tf.train.import_meta_graph('./lenet.meta')
    saver.restore(sess, "./lenet")
    num_examples = len(images)
    
    new_softmax_logits = tf.nn.softmax(logits)
    top_k = tf.nn.top_k(new_softmax_logits, k=3)
    
    print()
    sess.run(new_softmax_logits, feed_dict={x: images_test, keep_prob: 1.0})
    my_top_k = sess.run(top_k, feed_dict={x: images_test, keep_prob: 1.0})
    #print('shape',my_top_k[0])
    print()
    #print(my_top_k[0])
    for i in range(9):
        print('Top 3 largest probabilities', my_top_k[0][i]) # Printing first row to see probabilites
        print('Accuracy for image {} : '.format(i+1), my_top_k[0][i][0]*100, '%') # Printing first row first item

Top 3 largest probabilities [  9.99059260e-01   9.39751335e-04   8.33503350e-07]
Accuracy for image 1 :  99.9059259892 %
Top 3 largest probabilities [  1.00000000e+00   4.26131574e-10   5.84181101e-16]
Accuracy for image 2 :  100.0 %
Top 3 largest probabilities [  1.00000000e+00   1.07461122e-18   5.74002142e-23]
Accuracy for image 3 :  100.0 %
Top 3 largest probabilities [ 0.96365786  0.03386487  0.00247646]
Accuracy for image 4 :  96.3657855988 %
Top 3 largest probabilities [  9.98667955e-01   7.97871733e-04   2.66173272e-04]
Accuracy for image 5 :  99.8667955399 %
Top 3 largest probabilities [ 0.79864061  0.17153642  0.0109647 ]
Accuracy for image 6 :  79.8640608788 %
Top 3 largest probabilities [  9.99819458e-01   9.19139202e-05   3.13450219e-05]
Accuracy for image 7 :  99.9819457531 %
Top 3 largest probabilities [ 0.59855062  0.24148785  0.1049203 ]
Accuracy for image 8 :  59.8550617695 %
Top 3 largest probabilities [  1.00000000e+00   2.59115125e-12   3.17947437e-14]
Accuracy for image 9 :  100.0 %
In [29]:
# Playing with data
# Testing data within previous model to see will it predict better
# Model does not make sense due its same as above :)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    saver = tf.train.import_meta_graph('./lenet.meta')
    saver.restore(sess, "./lenet")
    num_examples = len(images)
    
    new_softmax_logits = tf.nn.softmax(logits)
    top_k = tf.nn.top_k(new_softmax_logits, k=3)
    
    print("Training...")
    print()
    for i in range(9):
        for offset in range(0, num_examples, BATCH_SIZE):
            end = offset + BATCH_SIZE
            sess.run(new_softmax_logits, feed_dict={x: images_test, keep_prob: 1.5})
            my_top_k = sess.run(top_k, feed_dict={x: images_test, keep_prob: 1.0})
            print(my_top_k[0][i][0])
        #validation_accuracy = evaluate(images_test, labels)
        #print("EPOCH {} ...".format(i+1))
        #print("Validation Accuracy = {:.3f}".format(validation_accuracy))
        #print()   
Training...

0.999059
1.0
1.0
0.963658
0.998668
0.798641
0.999819
0.598551
1.0

Analyze Performance

Output Top 5 Softmax Probabilities For Each Image Found on the Web

In [4]:
### Calculate the accuracy for these 5 new images. 
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
In [30]:
### Visualize the softmax probabilities here.
### Feel free to use as many code cells as needed.
### I have changed Dropout in this model and i see improvement in accuracy compering to model used and saved

### Some of the ideas in this code i used from Medium blog post: 
### https://medium.com/@vivek.yadav/improved-performance-of-deep-learning-neural-network-models-on-traffic-sign-classification-using-6355346da2dc#.txtoc558b
### https://chatbotslife.com/intricacies-of-traffic-sign-classification-with-tensorflow-8f994b1c8ba#.iuvl3gg82
### https://medium.com/@jeremyeshannon/udacity-self-driving-car-nanodegree-project-2-traffic-sign-classifier-f52d33d4be9f#.bspkhwstf

softmax_logits = tf.nn.softmax(logits)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    saver = tf.train.import_meta_graph('./lenet.meta')
    saver.restore(sess, "./lenet")
    new_softmax_logits = sess.run(softmax_logits, feed_dict={x: images_test, keep_prob: 1.0})
    new_top_k = sess.run(top_k, feed_dict={x: images_test, keep_prob: 1.0})
    
    fig, axs = plt.subplots(len(images),4, figsize=(12, 14))
    fig.subplots_adjust(hspace = .4, wspace=.2)
    axs = axs.ravel()

    for i, image in enumerate(images):
        axs[4*i].axis('off')
        axs[4*i].imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
        axs[4*i].set_title('input')
        guess1 = new_top_k[1][i][0]
        index1 = np.argwhere(y_valid == guess1)[0]
        axs[4*i+1].axis('off')
        axs[4*i+1].imshow(X_valid[index1].squeeze(), cmap='gray')
        axs[4*i+1].set_title('top guess: {} ({:.0f}%)'.format(guess1, 100*new_top_k[0][i][0]))
        guess2 = new_top_k[1][i][1]
        index2 = np.argwhere(y_valid == guess2)[0]
        axs[4*i+2].axis('off')
        axs[4*i+2].imshow(X_valid[index2].squeeze(), cmap='gray')
        axs[4*i+2].set_title('2nd guess: {} ({:.0f}%)'.format(guess2, 100*new_top_k[0][i][1]))
        guess3 = new_top_k[1][i][2]
        index3 = np.argwhere(y_valid == guess3)[0]
        axs[4*i+3].axis('off')
        axs[4*i+3].imshow(X_valid[index3].squeeze(), cmap='gray')
        axs[4*i+3].set_title('3rd guess: {} ({:.0f}%)'.format(guess3, 100*new_top_k[0][i][2]))

For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.

The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tk.nn.top_k is used to choose the three classes with the highest probability:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

In [6]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 
### Feel free to use as many code cells as needed.
In [42]:
# Imporved softmay representation per review of my submited project

fig, axs = plt.subplots(9,2, figsize=(10, 15))
axs = axs.ravel()

for i in range(len(new_softmax_logits)*2):
    if i%2 == 0:
        axs[i].axis('off')
        axs[i].imshow(cv2.cvtColor(images[i//2], cv2.COLOR_BGR2RGB))
    else:
        axs[i].bar(np.arange(n_classes), new_softmax_logits[(i-1)//2],color='r') 
        axs[i].set_ylabel(' Softmax')

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the IPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.